package com.cinema.entity.user;

import com.cinema.entity.hall.Hall;
import com.cinema.entity.movie.Movie;
import com.cinema.entity.movie.Schedule;
import com.cinema.service.HallService;
import com.cinema.service.MovieService;
import com.cinema.service.ScheduleService;
import com.cinema.util.DataStore;
import com.cinema.util.InputUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Scanner;

/**
 * 经理用户类，负责影片管理、场次安排等功能
 */
@Getter
@Setter
@AllArgsConstructor
public class ManagerUser extends AbstractUser implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    private final Scanner scanner = new Scanner(System.in);
    private final MovieService movieService = new MovieService();
    private final ScheduleService scheduleService = new ScheduleService();
    private final HallService hallService = new HallService();
    private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    // 保留带参构造器，移除重复的无参构造器定义
    public ManagerUser(String userId, String username, String password, LocalDateTime createTime, String userType, String phone) {
        super(userId, username, password, createTime, userType, phone);
    }

    @Override
    public void showMenu() {
        while (true) {
            System.out.println("\n===== 经理菜单 =====");
            System.out.println("1. 修改个人密码");
            System.out.println("2. 影片管理");
            System.out.println("3. 场次管理");
            System.out.println("4. 放映厅管理");
            System.out.println("5. 退出登录");
            System.out.print("请选择操作[1-5]：");

            int choice = InputUtil.getValidInt();
            switch (choice) {
                case 1:
                    handleChangePassword();
                    break;
                case 2:
                    handleMovieManagement();
                    break;
                case 3:
                    handleScheduleManagement();
                    break;
                case 4:
                    handleHallManagement();
                    break;
                case 5:
                    System.out.println("✅ 已退出登录");
                    return;
                default:
                    System.out.println("❌ 无效选择，请重新输入");
            }
        }
    }

    // 修改个人密码
    private void handleChangePassword() {
        System.out.print("请输入旧密码：");
        String oldPwd = scanner.next();
        System.out.print("请输入新密码：");
        String newPwd = scanner.next();

        if (super.changePassword(oldPwd, newPwd)) {
            System.out.println("✅ 密码修改成功");
        } else {
            System.out.println("❌ 旧密码错误，修改失败");
        }
    }

    // 影片管理子菜单
    private void handleMovieManagement() {
        System.out.println("\n===== 影片管理 =====");
        System.out.println("1. 添加新影片");
        System.out.println("2. 查看所有影片");
        System.out.println("3. 修改影片信息");
        System.out.println("4. 删除影片");
        System.out.println("5. 返回上一级");
        System.out.print("请选择[1-5]：");

        int choice = InputUtil.getValidInt();
        switch (choice) {
            case 1:
                addNewMovie();
                break;
            case 2:
                movieService.listAllMovies();
                break;
            case 3:
                updateMovie();
                break;
            case 4:
                deleteMovie();
                break;
            case 5:
                return;
            default:
                System.out.println("❌ 无效选择");
        }
        handleMovieManagement(); // 递归显示子菜单
    }

    // 添加新影片
    private void addNewMovie() {
        System.out.println("\n===== 添加新影片 =====");
        System.out.print("请输入影片名称：");
        String name = scanner.next();
        System.out.print("请输入导演：");
        String director = scanner.next();
        System.out.print("请输入主演：");
        String actors = scanner.next();
        System.out.print("请输入影片类型：");
        String type = scanner.next();
        System.out.print("请输入时长（分钟）：");
        int duration = InputUtil.getValidInt();
        System.out.print("请输入基础票价：");
        double price = scanner.nextDouble();
        scanner.nextLine(); // 清空缓冲区
        System.out.print("请输入影片简介：");
        String desc = scanner.nextLine();
        System.out.print("请输入评分（0-10）：");
        double score = scanner.nextDouble();

        // 生成影片ID（格式：M+3位数字）
        List<Movie> movies = DataStore.getInstance().getMovieList();
        String movieId = "M" + String.format("%03d", movies.size() + 1);

        Movie newMovie = new Movie(movieId, name, director, actors, type, duration, price, desc, score);
        movies.add(newMovie);
        DataStore.getInstance().updateMovieList();
        System.out.println("✅ 影片添加成功，影片ID：" + movieId);
    }

    // 修改影片信息
    private void updateMovie() {
        System.out.print("请输入要修改的影片ID：");
        String movieId = scanner.next();
        Movie movie = movieService.findMovieById(movieId);

        if (movie == null) {
            System.out.println("❌ 影片ID不存在");
            return;
        }

        System.out.print("请输入新的影片名称（原：" + movie.getMovieName() + "）：");
        String newName = scanner.next();
        if (!newName.isEmpty()) {
            movie.setMovieName(newName);
        }

        System.out.print("请输入新的基础票价（原：" + movie.getPrice() + "）：");
        String priceStr = scanner.next();
        if (!priceStr.isEmpty()) {
            movie.setPrice(Double.parseDouble(priceStr));
        }

        DataStore.getInstance().updateMovieList();
        System.out.println("✅ 影片信息更新成功");
    }

    // 删除影片
    private void deleteMovie() {
        System.out.print("请输入要删除的影片ID：");
        String movieId = scanner.next();
        Movie movie = movieService.findMovieById(movieId);

        if (movie == null) {
            System.out.println("❌ 影片ID不存在");
            return;
        }

        // 检查是否有关联场次
        List<Schedule> schedules = DataStore.getInstance().getScheduleList();
        for (Schedule s : schedules) {
            if (s.getMovie().getMovieId().equals(movieId)) {
                System.out.println("❌ 该影片存在关联场次，无法删除");
                return;
            }
        }

        DataStore.getInstance().getMovieList().remove(movie);
        DataStore.getInstance().updateMovieList();
        System.out.println("✅ 影片删除成功");
    }

    // 场次管理子菜单
    private void handleScheduleManagement() {
        System.out.println("\n===== 场次管理 =====");
        System.out.println("1. 添加新场次");
        System.out.println("2. 查看所有场次");
        System.out.println("3. 删除场次");
        System.out.println("4. 返回上一级");
        System.out.print("请选择[1-4]：");

        int choice = InputUtil.getValidInt();
        switch (choice) {
            case 1:
                addNewSchedule();
                break;
            case 2:
                scheduleService.listAllSchedules();
                break;
            case 3:
                deleteSchedule();
                break;
            case 4:
                return;
            default:
                System.out.println("❌ 无效选择");
        }
        handleScheduleManagement();
    }

    // 添加新场次
    private void addNewSchedule() {
        System.out.println("\n===== 添加新场次 =====");

        // 选择影片
        movieService.listAllMovies();
        System.out.print("请选择影片ID：");
        String movieId = scanner.next();
        Movie movie = movieService.findMovieById(movieId);
        if (movie == null) {
            System.out.println("❌ 影片不存在");
            return;
        }

        // 选择放映厅
        hallService.listAllHalls();
        System.out.print("请选择放映厅ID：");
        String hallId = scanner.next();
        Hall hall = hallService.findHallById(hallId);
        if (hall == null) {
            System.out.println("❌ 放映厅不存在");
            return;
        }

        // 输入放映时间
        System.out.print("请输入放映时间（格式：yyyy-MM-dd HH:mm）：");
        String timeStr = scanner.next();
        LocalDateTime showTime;
        try {
            showTime = LocalDateTime.parse(timeStr, dtf);
        } catch (Exception e) {
            System.out.println("❌ 时间格式错误");
            return;
        }

        // 输入票价
        System.out.print("请输入本场次票价：");
        double price = scanner.nextDouble();

        // 生成场次ID（格式：S+日期+放映厅）
        String dateStr = showTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String scheduleId = "S" + dateStr + "_" + hallId;

        // 创建场次
        Schedule newSchedule = new Schedule(
                scheduleId, movie, hall, showTime, price, 0, 0
        );
        DataStore.getInstance().getScheduleList().add(newSchedule);
        DataStore.getInstance().updateScheduleList();
        System.out.println("✅ 场次添加成功，场次ID：" + scheduleId);
    }

    // 删除场次
    private void deleteSchedule() {
        System.out.print("请输入要删除的场次ID：");
        String scheduleId = scanner.next();
        Schedule schedule = scheduleService.findScheduleById(scheduleId);

        if (schedule == null) {
            System.out.println("❌ 场次ID不存在");
            return;
        }

        // 检查是否已售票
        if (schedule.getSoldTickets() > 0) {
            System.out.println("❌ 该场次已有售票记录，无法删除");
            return;
        }

        DataStore.getInstance().getScheduleList().remove(schedule);
        DataStore.getInstance().updateScheduleList();
        System.out.println("✅ 场次删除成功");
    }

    // 放映厅管理子菜单
    private void handleHallManagement() {
        System.out.println("\n===== 放映厅管理 =====");
        System.out.println("1. 查看所有放映厅");
        System.out.println("2. 添加新放映厅");
        System.out.println("3. 返回上一级");
        System.out.print("请选择[1-3]：");

        int choice = InputUtil.getValidInt();
        switch (choice) {
            case 1:
                hallService.listAllHalls();
                break;
            case 2:
                addNewHall();
                break;
            case 3:
                return;
            default:
                System.out.println("❌ 无效选择");
        }
        handleHallManagement();
    }

    // 添加新放映厅
    private void addNewHall() {
        System.out.println("\n===== 添加新放映厅 =====");
        System.out.print("请输入放映厅名称（如：3号厅）：");
        String hallName = scanner.next();
        System.out.print("请输入行数：");
        int rows = InputUtil.getValidInt();
        System.out.print("请输入列数：");
        int cols = InputUtil.getValidInt();

        // 生成放映厅ID（格式：H+3位数字）
        List<Hall> halls = DataStore.getInstance().getHallList();
        String hallId = "H" + String.format("%03d", halls.size() + 1);

        Hall newHall = new Hall(hallId, hallName, rows, cols);
        halls.add(newHall);
        DataStore.getInstance().updateHallList();
        System.out.println("✅ 放映厅添加成功，ID：" + hallId);
    }
}

